import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Icon, Badge, Tooltip } from 'antd';
import ReactSeamlessScroll from 'react-seamless-scroll';
import screenfull from 'screenfull';
import LineStackChart from 'src/components/Chart/LineStackChart';
import PieChart from 'src/components/Chart/PieChart';
import BarStackChart from 'src/components/Chart/BarStackChart';
import Map from 'src/components/Chart/Map';
import { round } from 'src/utils/utils';
import ProgressBox from '../../components/ProgressBox';
import services from 'src/services/api';
import CodeLabel from 'src/components/CodeLabel';
import './index.less';
import moment from 'moment';
import Modal from 'src/components/Modal';
import RiskDashboardSetting from './setting';
import Clock from 'src/components/Clock';

export default function RiskDashboard() {
  const chart_height = (document.body.clientHeight - 80) * 0.33 - 24 - 40;
  const chart_height2 = (document.body.clientHeight - 80) * 0.66 - 24 - 80;
  const chart_width = document.body.clientWidth * 0.25 - 80;
  const [chartHeight, setChartHeight] = useState(chart_height);
  const [chartHeight2, setChartHeight2] = useState(chart_height2);
  const [chartWidth, setChartWidth] = useState(chart_width);

  const [request, setRequest] = useState({
    total: {
      value: 0,
    },
    pass: {
      value: 0,
      percent: 0,
    },
    review: {
      value: 0,
      percent: 0,
    },
    reject: {
      value: 0,
      percent: 0,
    },
  });

  const [riskTrend, setRiskTrend] = useState([]);
  const [riskStatistics, setRiskStatistics] = useState([]);
  const [requestSource, setRequestSource] = useState([]);
  const [cityTop, setCityTop] = useState([]);
  const [requestList, setRequestList] = useState([]);
  const [eventRatio, setEventRatio] = useState([]);
  const [appId, setAppId] = useState(-1);
  const [productId, setProductId] = useState('');
  const [appLists, setAppLists] = useState([]);
  const [productList, setProductList] = useState([]);

  const timeHandle = useRef(null);
  const timeInterval = useRef(5000);

  useEffect(() => {
    window.addEventListener('resize', () => {
      const chart_height = (document.body.clientHeight - 80) * 0.33 - 24 - 60;
      const chart_height2 = (document.body.clientHeight - 80) * 0.66 - 24 - 80;
      setChartHeight(chart_height);
      setChartHeight2(chart_height2);
      setChartWidth(document.body.clientWidth * 0.25 - 80);
    });
    return () => {
      window.removeEventListener('resize', () => {});
    };
  }, []);

  useEffect(() => {
    getAppCodeList();
    getProductCodeList();
    getStatistics();
    getSetting();

    return () => {
      clearInterval(timeHandle.current);
      timeHandle.current = null;
    };
  }, []);

  // 获取配置
  function getSetting() {
    services.riskDashboard.getSetting({}).then((res) => {
      if (res.code === 0) {
        setAppId(res.data.dashboard_config.app_id);
        setProductId(res.data.dashboard_config.product_id);
        timeInterval.current = res.data.dashboard_config.refresh_frequency * 1000;
        clearInterval(timeHandle.current); // 清空定时器

        // 重设定时器
        timeHandle.current = setInterval(() => {
          getStatistics();
        }, timeInterval.current);
      }
    });
  }

  function getStatistics() {
    getRequst();
    getRiskTrend();
    getRiskStatistics();
    getRequestSource();
    getCityTop();
    getRequestList();
    getEventRatio();
  }

  //渠道列表请求
  function getAppCodeList() {
    services.application.getAllAppCodeList().then((res) => {
      if (res.code === 0) {
        setAppLists(res.data);
      }
    });
  }
  // 产品列表请求
  function getProductCodeList({ app_id = -1, event_id = -1 } = {}) {
    services.product.getProductCodeList({ app_id, event_id }).then((res) => {
      if (res.code === 0) {
        setProductList(res.data);
      }
    });
  }

  // 今日请求
  function getRequst() {
    services.riskDashboard.request({}).then((res) => {
      if (res.code === 0) {
        if (res.data.length > 0) {
          const [total, pass, review, reject] = res.data;

          const request = {
            total: {
              value: total.value,
            },
            pass: {
              value: pass.value,
              percent: total.value > 0 ? (round(pass.value / total.value, 2) * 100).toFixed(0) : 0,
            },
            review: {
              value: review.value,
              percent: total.value > 0 ? (round(review.value / total.value, 2) * 100).toFixed(0) : 0,
            },
            reject: {
              value: reject.value,
              percent: total.value > 0 ? (round(reject.value / total.value, 2) * 100).toFixed(0) : 0,
            },
          };
          setRequest(request);
        }
      }
    });
  }

  // 实时风险趋势
  function getRiskTrend() {
    services.riskDashboard.ruleTrend({}).then((res) => {
      if (res.code === 0) {
        setRiskTrend(res.data);
      }
    });
  }

  // 近7日风险统计
  function getRiskStatistics() {
    services.riskDashboard.riskStatistics({}).then((res) => {
      if (res.code === 0) {
        setRiskStatistics(res.data.filter((it, index) => index > 0));
      }
    });
  }

  // 城市来源
  function getRequestSource() {
    services.riskDashboard.requestSource({}).then((res) => {
      if (res.code === 0) {
        const citys = res.data.map((it, index) => it.key);
        setRequestSource(citys);
      }
    });
  }

  // 城市排名
  function getCityTop() {
    services.riskDashboard.cityTop({}).then((res) => {
      if (res.code === 0) {
        setCityTop(res.data);
      }
    });
  }

  // 请求来源城市排名
  function getRequestList() {
    services.riskDashboard.requestList({}).then((res) => {
      if (res.code === 0) {
        setRequestList(res.data);
      }
    });
  }

  // 请求时间占比
  function getEventRatio() {
    services.riskDashboard.eventRatio({}).then((res) => {
      if (res.code === 0) {
        setEventRatio(res.data);
      }
    });
  }

  function showSetting() {
    Modal.open({
      title: '风险大盘设置',
      width: '400px',
      content: (
        <RiskDashboardSetting
          app_id={appId}
          product_id={productId}
          refresh_frequency={timeInterval.current / 1000}
          reSetFrequency={(res) => reSetFrequency(res)}
          closeModal={() => Modal.close()}
          appLists={appLists}
          productList={productList}
        />
      ),
      isOkBtn: false,
      maskClosable: false,
      isCancelBtn: false,
    });
  }

  //重置刷新频率
  function reSetFrequency() {
    getStatistics(); // 立即刷新数据
    getSetting();
    Modal.close();
  }

  // 点击全屏
  function screen() {
    if (screenfull.isEnabled) {
      screenfull.toggle();
      screenfull.on('error', (event) => {
        console.error('Failed to enable fullscreen', event);
      });
    }
  }

  const cityTotal = cityTop.reduce((total, it) => {
    total += it.request;
    return total;
  }, 0);

  const getReplaceName = (name) => {
    const arr = [
      {
        old: '请求总量',
        new: '今日申请人数',
      },
      {
        old: '通过请求量',
        new: '通过人数',
      },
      {
        old: '复核请求量',
        new: '人工审核人数',
      },
      {
        old: '拒绝请求量',
        new: '拒绝人数',
      },
    ];
    const cur = arr.find((it) => it.old === name) || {};
    return cur.new;
  };

  return (
    <div className='risk-dashboard'>
      <div className='hd'>
        <Row type='flex' justify='space-between'>
          <Col span={6}>
            <div className='time'>
              <Icon type='clock-circle' />
              <Clock />
            </div>
          </Col>
          <Col span={6} className='title'>
            风险大盘
          </Col>
          <Col span={6} className='setting'>
            <Icon type='setting' onClick={() => showSetting()} />
            <Icon type='fullscreen' onClick={() => screen()} />
          </Col>
        </Row>
      </div>
      <Row type='flex' justify='space-between' gutter={20} className='row'>
        <Col span={6} className='col'>
          <div className=' dashboard-box-2 flex-v'>
            <div className='dashboard-box dashboard-box-3 flex-v'>
              <Row className='dashoard-box-item'>
                <Col>
                  <div>
                    <h5>今日申请人数</h5>
                    <Row type='flex' align='middle'>
                      <Col>
                        <span className='count'>{request.total.value}</span>
                      </Col>
                      <Col>次</Col>
                    </Row>
                  </div>
                </Col>
              </Row>
              <Row type='flex' justify='space-between' align='middle' className='dashoard-box-item'>
                <Col>
                  <div>
                    <h5>通过人数</h5>
                    <Row type='flex' align='middle'>
                      <Col>
                        <span className='count' style={{ color: 'rgb(33, 209, 180)' }}>
                          {request.pass.value}
                        </span>
                      </Col>
                      <Col>次</Col>
                    </Row>
                  </div>
                </Col>
                <Col>
                  <span className='percent'>
                    <Badge
                      count={request.pass.percent + '%'}
                      style={{ backgroundColor: 'rgb(33, 209, 180)', marginLeft: '10px' }}
                    />
                  </span>
                </Col>
              </Row>
              <Row type='flex' justify='space-between' align='middle' className='dashoard-box-item'>
                <Col>
                  <div>
                    <h5>人工审核人数</h5>
                    <Row type='flex' align='middle'>
                      <Col>
                        <span className='count' style={{ color: 'rgb(247, 129, 32)' }}>
                          {request.review.value}
                        </span>
                      </Col>
                      <Col>次</Col>
                    </Row>
                  </div>
                </Col>
                <Col>
                  <span className='percent'>
                    <Badge
                      count={request.review.percent + '%'}
                      style={{ backgroundColor: 'rgb(247, 129, 32)', marginLeft: '10px' }}
                    />
                  </span>
                </Col>
              </Row>
              <Row type='flex' justify='space-between' align='middle' className='dashoard-box-item'>
                <Col>
                  <div>
                    <h5>拒绝人数</h5>
                    <Row type='flex' align='middle'>
                      <Col>
                        <span className='count' style={{ color: 'rgb(247, 76, 33)' }}>
                          {request.reject.value}
                        </span>
                      </Col>
                      <Col>次</Col>
                    </Row>
                  </div>
                </Col>
                <Col>
                  <span className='percent'>
                    <Badge
                      count={request.reject.percent + '%'}
                      style={{ backgroundColor: 'rgb(247, 76, 33)', marginLeft: '10px' }}
                    />
                  </span>
                </Col>
              </Row>
            </div>
            <div className='dashboard-box dashboard-box-3' style={{ marginBottom: 0 }}>
              <div className='inner'>
                <h4>实时风险趋势</h4>
                {riskTrend.length > 0 && (
                  <LineStackChart
                    id='cpu'
                    width='100%'
                    height={chartHeight}
                    dataSource={riskTrend.map((it) => {
                      return {
                        ...it,
                        name: getReplaceName(it.name),
                      };
                    })}
                    dataRender={(it) => it.requests}
                    colors={['#5e7ea2', '#5e7ea2', '#ffffff']}
                    colorOptions={[
                      '#006eff',
                      'rgb(33, 209, 180)',
                      'rgb(247, 129, 32)',
                      'rgb(247, 76, 33)',
                      '#61a0a8',
                      '#d48265',
                      '#91c7ae',
                      '#749f83',
                      '#ca8622',
                      '#bda29a',
                      '#6e7074',
                      '#546570',
                      '#c4ccd3',
                    ]}
                    xRender={(item) => {
                      return moment(item.index).format('HH:mm');
                    }}
                    legendSetting={{ padding: 10, bottom: 0 }}
                  />
                )}
              </div>
            </div>
          </div>
          <div className='dashboard-box dashboard-box-1'>
            <div className='inner'>
              <h4>近七天风险统计</h4>
              <BarStackChart
                id='bar'
                width='100%'
                height={chartHeight}
                xAxisKey='index'
                isDd={true}
                dataKey='requests'
                colors={['#5e7ea2', '#5e7ea2', '#ffffff']}
                colorOptions={[
                  'rgb(33, 209, 180)',
                  'rgb(247, 129, 32)',
                  'rgb(247, 76, 33)',
                  '#61a0a8',
                  '#d48265',
                  '#91c7ae',
                  '#749f83',
                  '#ca8622',
                  '#bda29a',
                  '#6e7074',
                  '#546570',
                  '#c4ccd3',
                ]}
                barWidth={15}
                dataSource={riskStatistics.map((it) => {
                  return {
                    ...it,
                    name: getReplaceName(it.name),
                  };
                })}
                xRender={(item) => {
                  return moment(item.index).format('MM/DD');
                }}
                legendSetting={{ padding: 10 }}
              />
            </div>
          </div>
        </Col>
        <Col span={12} className='col'>
          <div className='dashboard-box dashboard-box-2 dashboard-box-noborder'>
            <div className='inner'>
              <h4>实时请求来源</h4>
              <Map
                location={requestSource}
                width='100%'
                height={chartHeight2}
                colors={['transparent', '#5e7ea2', '#ddb926']}
              />
            </div>
          </div>
          <div className='dashboard-box dashboard-box-1'>
            <div className='inner'>
              <h4>实时决策结果</h4>
              <div className='inner-con'>
                <Row gutter={10} className='table-hd'>
                  <Col span={4}>请求时间</Col>
                  <Col span={3}>所属渠道</Col>
                  <Col span={3}>所属产品</Col>
                  <Col span={3}>请求类型</Col>
                  <Col span={3}>命中结果</Col>
                  <Col span={4}>命中策略</Col>
                  <Col span={4}>IP地理位置</Col>
                </Row>
                <ReactSeamlessScroll style={{ width: '100%', height: chartHeight + 'px' }}>
                  {requestList.map((it) => {
                    return (
                      <Row gutter={10} className='table-item' key={it.req_id}>
                        <Col span={4}>
                          <div className='overflowtext'>
                            <Tooltip title={it.req_time}>{it.req_time}</Tooltip>
                          </div>
                        </Col>
                        <Col span={3}>
                          <div className='overflowtext'>
                            <Tooltip title={it.app_name}>{it.app_name}</Tooltip>
                          </div>
                        </Col>
                        <Col span={3}>
                          <div className='overflowtext'>
                            <Tooltip title={it.product_name}>{it.product_name}</Tooltip>
                          </div>
                        </Col>
                        <Col span={3}>
                          <div className='overflowtext'>
                            <Tooltip title={it.event_name}>{it.event_name}</Tooltip>
                          </div>
                        </Col>
                        <Col span={3}>
                          <CodeLabel code='risk_level' value={it.risk_level} />
                        </Col>
                        <Col span={4}>
                          <div className='overflowtext'>
                            <Tooltip title={it.risk_type_names ? it.risk_type_names.join(',') : ''}>
                              {it.risk_type_names ? it.risk_type_names.join(',') : ''}
                            </Tooltip>
                          </div>
                        </Col>
                        <Col span={4}>{it.ip_loc}</Col>
                      </Row>
                    );
                  })}
                </ReactSeamlessScroll>
              </div>
            </div>
          </div>
        </Col>
        <Col span={6} className='col'>
          <div className='dashboard-box dashboard-box-2'>
            <div className='inner risk-city'>
              <h4>请求来源城市排行</h4>
              <div className='inner'>
                <ProgressBox
                  keyValue={['key', 'request']}
                  className='dark'
                  strokeColor={{
                    '0%': '#108ee9',
                    '100%': '#87d068',
                  }}
                  dataSource={cityTop}
                  total={cityTotal}
                  renderLabel={(record, index) => {
                    return (
                      <>
                        <span className='index'>{index + 1}</span>
                        <span className='city'>{record.key}</span>
                      </>
                    );
                  }}
                  renderValue={(record, index) => {
                    return <span className='value'>{record.request}</span>;
                  }}
                />
              </div>
            </div>
          </div>
          <div className='dashboard-box dashboard-box-1'>
            <div className='inner'>
              <h4>请求类型占比</h4>
              <div className='inner'>
                <PieChart
                  width={chartWidth}
                  height={chartHeight}
                  seriesBottom='20'
                  id='events'
                  orient='horizontal'
                  legendSetting={{ padding: 10, bottom: 0, show: false }}
                  colors={['#5e7ea2']}
                  colorOptions={[
                    '#006eff',
                    'rgb(33, 209, 180)',
                    'rgb(247, 129, 32)',
                    'rgb(247, 76, 33)',
                    '#61a0a8',
                    '#d48265',
                    '#91c7ae',
                    '#749f83',
                    '#ca8622',
                    '#bda29a',
                    '#6e7074',
                    '#546570',
                    '#c4ccd3',
                  ]}
                  dataSource={eventRatio.map((it) => {
                    it.name = it.event_name;
                    it.value = it.hit_times;
                    return it;
                  })}
                />
              </div>
            </div>
          </div>
        </Col>
      </Row>
    </div>
  );
}
